// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: tianqiang

#include "coin2/exchange/base/order/risk_undetected_position.h"

#include <sstream>

#include <glog/logging.h>

namespace coin2::exchange::base::order {

void RiskUndetectedPosition::HandleUndetectedPosition(
    std::vector<ProductPosition>&& undetected_position) {
  for (auto&& position : undetected_position) {
    std::string symbol = position.symbol();
    undetected_position_map_.emplace(std::move(symbol), position);
  }
}

void RiskUndetectedPosition::ManageRisk(int64_t ts) {
  // check every 5s
  if (last_update_timestamp_ + 5'000'000'000LL > ts) {
    return;
  }
  last_update_timestamp_ = ts;

  if (undetected_position_map_.empty()) {
    return;
  }

  std::stringstream ss;
  coin::proto::RiskEvent risk_event;
  for (auto& pair : undetected_position_map_) {
    ss << "symbol:" << pair.first << " long:" << pair.second.long_position()
       << " short:" << pair.second.short_position() << " net:" << pair.second.net_position() << ",";

    auto* risk_undetect_position = risk_event.add_risk_undetect_position();
    *risk_undetect_position = std::move(pair.second);
  }
  LOG(WARNING) << "[RiskUndetectedPosition] total: " << undetected_position_map_.size() << " <"
               << ss.str() << ">";

  undetected_position_map_.clear();

  risk_event.set_risk_event_type(coin::proto::RiskEvent::RISK_UNDETECTED_POSITION);
  risk_event_handler_(risk_event);
}

}  // namespace coin2::exchange::base::order
